package io.github.talelin.latticy.service.impl;

import cn.hutool.core.lang.Assert;
import io.github.talelin.latticy.dto.rule.chargeCondition.ChargeConditionUpdateDTO;
import io.github.talelin.latticy.dto.rule.chargeCondition.ChargeRuleUpdateDTO;
import io.github.talelin.latticy.model.ChargeAbsoluteDO;
import io.github.talelin.latticy.model.ChargeConditionDO;
import io.github.talelin.latticy.mapper.ChargeConditionMapper;
import io.github.talelin.latticy.service.ChargeAbsoluteService;
import io.github.talelin.latticy.service.ChargeConditionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.github.talelin.latticy.service.RulesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author generator@wulongbo
 * @since 2022-08-25
 */
@Service
public class ChargeConditionServiceImpl extends ServiceImpl<ChargeConditionMapper, ChargeConditionDO> implements ChargeConditionService {

    @Autowired
    private RulesService rulesService;

    @Autowired
    private ChargeAbsoluteService chargeAbsoluteService;

    @Transactional
    @Override
    public boolean updateRuleEngine(ChargeRuleUpdateDTO dto) {
        // 1: 更新rules表基础费用
        rulesService.updateBaseCostById(dto.getRuleId(), dto.getBaseCost());
        // 2: 更新charge_condition条件表
        this.deleteChargeConditionByChargeItemId(dto.getId());
        List<ChargeConditionDO> ccList = dto.getConditionList().parallelStream().map(cdt->new ChargeConditionDO(cdt,dto.getId())).collect(Collectors.toList());
        this.saveBatch(ccList);
        // 3: 更新charge_absolute结果表
        chargeAbsoluteService.deleteChargeAbsoluteByChargeItemId(dto.getId());
        List<ChargeAbsoluteDO> caList = dto.getAbsoluteList().parallelStream().map(abs->new ChargeAbsoluteDO(abs,dto.getId())).collect(Collectors.toList());
        return chargeAbsoluteService.saveBatch(caList);
    }

    @Override
    public boolean deleteChargeConditionByChargeItemId(Integer chargeItemId) {
        return this.baseMapper.deleteChargeConditionByChargeItemId(chargeItemId) > 0;
    }
}
